﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.ApplicationBlocks.Data;
using System.Configuration;
using BE;
using BC;

namespace ModuleDuoc
{
    public partial class frmDuTruMuaThuoc : ModuleDuoc.Base.frmBase
    {
        string sql;
        DataTable dt = new DataTable();
        string _tennhanvien;
        private static string type;
        public frmDuTruMuaThuoc()
        {
            InitializeComponent();
        }

        private void frmDuTruMuaThuoc_Load(object sender, EventArgs e)
        {
            this.lblTitle.Text = "DỰ TRÙ THUỐC";
            dgvCT.AutoGenerateColumns = false;
            dgvLeft.AutoGenerateColumns = false;
            loadSoPhieu();
            fillCboxThuoc();
            pnlDetailt.Enabled = false;

            btnSave.Enabled = false;
            btnInPhieu.Enabled = false;
            btnEdit.Enabled = false;
            btnHuyPhieu.Enabled = false;
            txtNguoiLap.Text = _tennhanvien;
        }

        private void loadSoPhieu()
        {
            //ZD_DuTruMuaThuocBC bc = new ZD_DuTruMuaThuocBC();
            //dt = bc.GetAll();
            //dgvLeft.DataSource = dt;
            //dgvLeft.Rows.Clear();
            sql = "SELECT DuTru_ID, ThoiGian FROM zD_DuTruMuaThuoc " +
                    "WHERE huy = 0 and ThoiGian = '"+dateSearch.Text+"'";
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            dgvLeft.DataSource = dt;
        }

        private void fillCboxThuoc()
        {
            BC.ZD_DM_THUOCBC bc = new BC.ZD_DM_THUOCBC();
            this.cboxTenThuoc.DataSource = bc.GetAll();
            this.cboxTenThuoc.DisplayMember = "TenVT";
            this.cboxTenThuoc.ValueMember = "TenVT";
        }

        private void cboxTenThuoc_SelectedValueChanged(object sender, EventArgs e)
        {
            sql = "SELECT TOP 1 htn.TENVT, htn.Ten, htn.nhacc, htn.dongianhap, htn.ngaylap " +
                    "FROM thongke.hienbuf_ThuocNew htn " +
                    "WHERE htn.TENVT = N'"+cboxTenThuoc.Text+"' " +
                    "ORDER BY ngaylap desc";
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                txtDVT.Text = dt.Rows[0]["Ten"].ToString();
                cboxNuocSX.Text = dt.Rows[0]["NhaCC"].ToString();
                txtDonGia.Text = dt.Rows[0]["DonGiaNhap"].ToString();;
                getSLBan();
            }
            else
            {
                //MessageBox.Show("Không tìm thấy thuốc này!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDVT.Text = "";
                txtSLBan.Text = "0";
                txtSLTon.Text = "0";
                txtSLDuTru.Text = "0";
                txtDonGia.Text = "";
                txtThanhTien.Text = "";
                txtGhiChu.Text = "";
            }
        }

        private void getSLBan() // lấy số lượng bán & tồn trong tháng trước
        {
            int thang = Int32.Parse(date.Text.Substring(0, 2)) - 1;
            int nam = Int32.Parse(date.Text.Substring(3, 4));
            sql = "SELECT top 1 zdbt.tenvt, sum(zdbt.slxuat) as xuat, sum(zdk.soluong) as sl " +
                    "FROM zD_bcTonkhoth zdbt " +
                    "INNER JOIN zD_KIEMKE2012 zdk ON zdk.mavach = zdbt.mavach " +
                    "WHERE zdbt.tenvt = N'"+cboxTenThuoc.Text+"' AND zdk.thang = "+thang+" AND zdk.nam = "+nam+" " +
                    "GROUP BY zdbt.tenvt";
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                txtSLBan.Text = dt.Rows[0]["xuat"].ToString();
                txtSLTon.Text = dt.Rows[0]["sl"].ToString();
            }
            else
            {
                txtSLBan.Text = "";
                txtSLTon.Text = "";
            }
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            dgvCT.Rows.Add("",cboxTenThuoc.Text, cboxNuocSX.Text, txtDVT.Text, txtSLBan.Text, txtSLTon.Text, txtSLDuTru.Text,"", txtDonGia.Text, txtThanhTien.Text, txtGhiChuCT.Text);
        }

        private void btnHuyChon_Click(object sender, EventArgs e)
        {
            if (dgvCT.CurrentRow.Cells["DuTruCT_ID"].Value.ToString() == "")
            {
                for (int i = dgvCT.SelectedRows.Count - 1; i >= 0; i--)
                {
                    this.dgvCT.Rows.RemoveAt(dgvCT.SelectedRows[i].Index);
                }
            }
            else
            {
                MessageBox.Show("Không hủy được thuốc này", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtSLDuTru_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtThanhTien.Text = (float.Parse(txtDonGia.Text) * float.Parse(txtSLDuTru.Text)).ToString();
            }
            catch { }
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtThanhTien.Text = (float.Parse(txtDonGia.Text) * float.Parse(txtSLDuTru.Text)).ToString();
            }
            catch { }
        }

        #region btn
        public override void btnThemMoi_Click(object sender, EventArgs e)
        {
            base.btnThemMoi_Click(sender, e);
            type = "insert";
            pnlDetailt.Enabled = true; 
            btnSave.Enabled = true;
            btnEdit.Enabled = false;
            btnHuyPhieu.Enabled = false;
            clear();
        }
        private void clear()
        {
            txtNguoiLap.Text = _tennhanvien;
            txtGhiChu.Text = "";
            dgvCT.Rows.Clear();
        }

        public override void btnSave_Click(object sender, EventArgs e)
        {
            base.btnSave_Click(sender, e);
            btnInPhieu.Enabled = false;
            btnEdit.Enabled = false;
            btnHuyPhieu.Enabled = false;
            btnSave.Enabled = false;
            if (pnlDetailt.Enabled == true && dgvCT.Rows.Count > 0)
            {
                capNhat();
                capNhatCT();
                MessageBox.Show("Cập nhật thành công", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                pnlDetailt.Enabled = false;
            }
            else
            {
                MessageBox.Show("Dữ liệu không hợp lệ!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            loadSoPhieu();
        }

        private void capNhat()
        {
            ZD_DuTruMuaThuoc be = new ZD_DuTruMuaThuoc();
            ZD_DuTruMuaThuocBC bc = new ZD_DuTruMuaThuocBC();

            be.ThoiGian = date.Text;
            be.NhanVien = txtNguoiLap.Text;
            be.PhongBan = cboxPhongBan.Text;
            be.NgayLap = DateTime.Now;
            be.GhiChu = txtGhiChu.Text;
            be.Huy = 0;

            if (type == "insert")
            {
                bc.Insert(be);
            }
            else if (type == "update")
            {
                be.DuTru_ID = Int32.Parse(dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString());
                bc.Update(be);
            }
        }
        private string getMax() //Lẫy max Dutruthuoc
        {
            sql = "SELECT MAX(DuTru_ID) AS id FROM zd_DuTruMuaThuoc";
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString();
            }
            else
            {
                return "1";
            }
        }
        private void capNhatCT()
        {
            ZD_DuTruMuaThuocCT be = new ZD_DuTruMuaThuocCT();
            ZD_DuTruMuaThuocCTBC bc = new ZD_DuTruMuaThuocCTBC();

            be.DuTru_ID = Int32.Parse(getMax()); //get max table DuTruMuaThuoc;
            for (int i = 0; i < this.dgvCT.Rows.Count; i++)
            {
                be.TenVT = dgvCT.Rows[i].Cells["tenthuoc"].Value.ToString();
                be.DVT = dgvCT.Rows[i].Cells["dvt"].Value.ToString();
                be.NuocSX = dgvCT.Rows[i].Cells["nuocsx"].Value.ToString();
                be.SLban = Int32.Parse(dgvCT.Rows[i].Cells["slban"].Value.ToString());
                be.SLton = Int32.Parse(dgvCT.Rows[i].Cells["slton"].Value.ToString());
                be.SLduTru = Int32.Parse(dgvCT.Rows[i].Cells["sldutru"].Value.ToString());
                be.DonGia = float.Parse(dgvCT.Rows[i].Cells["dongia"].Value.ToString());
                be.GhiChu = dgvCT.Rows[i].Cells["ghichu"].Value.ToString();

                if (type == "insert")
                {
                    bc.Insert(be);
                }
                else if (type == "update")
                {
                    //MessageBox.Show(dgvCT.Rows[i].Cells["DuTruCT_ID"].Value.ToString());
                    try
                    {
                        if (dgvCT.Rows[i].Cells["DuTruCT_ID"].Value.ToString() == "")
                        {
                            be.DuTru_ID = Int32.Parse(dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString());
                            bc.Insert(be);
                        }
                        else
                        {
                            be.DuTruCT_ID = Int32.Parse(dgvCT.Rows[i].Cells["DuTruCT_ID"].Value.ToString());
                            be.DuTru_ID = Int32.Parse(dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString());
                            bc.Update(be);
                        }
                    }
                    catch { }
                }
            }
        }

        public override void btnEdit_Click(object sender, EventArgs e)
        {
            base.btnEdit_Click(sender, e);
            type = "update";
            pnlDetailt.Enabled = true;
            btnSave.Enabled = true;
        }
        public override void btnHuyPhieu_Click(object sender, EventArgs e)
        {
            base.btnHuyPhieu_Click(sender, e);
            if (dgvCT.Rows.Count > 0)
            {
                if (MessageBox.Show("Chọn hủy phiếu này?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    huyPhieu();
                    pnlDetailt.Enabled = false;
                    dgvCT.Rows.Clear();
                }
            }
        }
        private void huyPhieu()
        {
            string sql = "UPDATE [QUANLYVTXN].[dbo].[zD_DuTruMuaThuoc] " +
                            "SET [Huy] = 1 " +
                            "WHERE DuTru_ID = "+dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString()+"";
            SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql);
            MessageBox.Show("Hủy phiếu thành công", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            loadSoPhieu();
            //getSoPhieu()
        }
        public override void btnInPhieu_Click(object sender, EventArgs e)
        {
            base.btnInPhieu_Click(sender, e);
            if (dgvCT.Rows.Count > 0)
            {
                sql = "SELECT TenVT, NuocSX, DVT, SLban, SLton, SLduTru, DonGia,GhiChu,SLduTru * DonGia AS ThanhTien " +
                        "FROM zD_DuTruMuaThuocCT " +
                        "WHERE DuTru_ID = " + dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString() + "";
                DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                frmShowReport frm = new frmShowReport(2);
                frmShowReport.strC = frmShowReport.BC.DUTRUMUATHUOC;
                frmShowReport._dt = dt;
                frmShowReport._thoiGian = date.Text;
                frmShowReport._so = dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString();
                frmShowReport._nhanvien = txtNguoiLap.Text;
                frmShowReport._phongban = cboxPhongBan.Text;
                frm.ShowDialog();
            }
        }
        private void report()
        { 
        
        }

        public override void btnExit_Click(object sender, EventArgs e)
        {
            base.btnExit_Click(sender, e);
        }
        #endregion

        private void dgvLeft_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            btnInPhieu.Enabled = true;
            btnEdit.Enabled = true;
            btnHuyPhieu.Enabled = true;

            getSoPhieu();
            dgvCT.Rows.Clear();
            getSoPhieuCT();
        }

        private void getSoPhieu()
        {
            sql = "SELECT ThoiGian,NhanVien,PhongBan,GhiChu,NgayLap FROM zD_DuTruMuaThuoc " +
                    "WHERE DuTru_ID = "+dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString()+" ";
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];

            date.Text = dt.Rows[0]["ThoiGian"].ToString();
            txtNguoiLap.Text = dt.Rows[0]["NhanVien"].ToString();
            cboxPhongBan.Text = dt.Rows[0]["PhongBan"].ToString();
            txtGhiChu.Text = dt.Rows[0]["GhiChu"].ToString();
            dateLapPhieu.Text = dt.Rows[0]["NgayLap"].ToString();
        }
        private void getSoPhieuCT()
        {
            dgvCT.Rows.Clear();
            sql = "SELECT DuTruCT_ID, DuTru_ID, TenVT, NuocSX, DVT, SLban, SLton, SLduTru, DonGia,GhiChu " +
                    "FROM zD_DuTruMuaThuocCT " +
                    "WHERE DuTru_ID = " + dgvLeft.CurrentRow.Cells["DuTru_ID"].Value.ToString() + "";
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];            
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dgvCT.Rows.Add(dt.Rows[i]["DuTruCT_ID"].ToString(), dt.Rows[i]["TenVT"].ToString(), dt.Rows[i]["NuocSX"].ToString(),
                    dt.Rows[i]["DVT"].ToString(), dt.Rows[i]["SLban"].ToString(), dt.Rows[i]["SLton"].ToString(),
                    dt.Rows[i]["SLduTru"].ToString(), "", dt.Rows[i]["DonGia"].ToString(),
                    Int32.Parse(dt.Rows[i]["SLduTru"].ToString()) * float.Parse(dt.Rows[i]["DonGia"].ToString()), dt.Rows[i]["GhiChu"].ToString());
            }
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            loadSoPhieu();
        }
    }
}
